package com.heima.begavior.service.impl;

import com.heima.begavior.service.ApBehaviorEntryService;
import com.heima.begavior.service.ApLikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.Date;

@Service
@Slf4j
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {

   @Autowired
    MongoTemplate mongoTemplate;

   @Autowired
    ApBehaviorEntryService apBehaviorEntryService;


    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //校验参数
        ApUser user = AppThreadLocalUtils.getUser();

        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        //获取行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());

        if (apBehaviorEntry==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未获取到对应的行为实体信息");
        }
        int operation = dto.getOperation().intValue();
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("articleId").is(dto.getArticleId()));

        if(operation == 0){ // 点赞
            ApLikesBehavior likesBehavior = mongoTemplate.findOne(query, ApLikesBehavior.class);
            // 如果operation 0 ==> 点赞     添加点赞行为数据
            if (likesBehavior!=null) {
//                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"请勿重复点赞");
            }else {
                likesBehavior = new ApLikesBehavior();
                likesBehavior.setEntryId(apBehaviorEntry.getId());
                likesBehavior.setArticleId(dto.getArticleId());
                likesBehavior.setType((short)0);
                likesBehavior.setOperation((short)0);
                likesBehavior.setCreatedTime(new Date());
                mongoTemplate.save(likesBehavior);
            }

        }else {
            // 如果operation 1 ==> 取消赞    删除点赞行为数据
            mongoTemplate.remove(query,ApLikesBehavior.class);
        }
        return ResponseResult.okResult();
    }
}
